import { ref } from "vue"
import store from "@/store"
import { defineStore } from "pinia"
import { useTagsViewStore } from "./tags-view"
import { useSettingsStore } from "./settings"
import { getToken, removeToken, setToken } from "@/utils/cache/cookies"
import { resetRouter } from "@/router"
import { loginApi } from "@/api/system-api/user"
import { type LoginRequestData } from "@/api/system-api/user/types/login"
import { Userinfo } from "@/api/system-api/user/types/user"

export const useUserStore = defineStore("user", () => {
  const token = ref<string>(getToken() || "")
  const roles = ref<string[]>([])
  const username = ref<string>("")
  const userinfo = ref<Userinfo>()
  const tagsViewStore = useTagsViewStore()
  const settingsStore = useSettingsStore()

  /** 登录 */
  const login = async ({ account, password, code }: LoginRequestData) => {
    //'token-admin'
    const { items } = await loginApi({ account, password, code })
    setToken(items)
    token.value = items
  }
  /** 获取用户详情 */
  const getInfo = () => {
    if (userinfo.value == null) {
      const token = getToken() || ""
      let userStr = token?.split(".")[1].replace(/\s/g, "+")
      userStr = Buffer.from(userStr, "base64").toString()
      const user = JSON.parse(userStr)
      userinfo.value = user as Userinfo
    }
  }
  /** 模拟角色变化 */
  const changeRoles = async (role: string) => {
    const newToken = "token-" + role
    token.value = newToken
    setToken(newToken)
    // 用刷新页面代替重新登录
    window.location.reload()
  }
  /** 登出 */
  const logout = () => {
    removeToken()
    token.value = ""
    roles.value = []
    resetRouter()
    _resetTagsView()
  }
  /** 重置 Token */
  const resetToken = () => {
    removeToken()
    token.value = ""
    roles.value = []
  }
  /** 重置 Visited Views 和 Cached Views */
  const _resetTagsView = () => {
    if (!settingsStore.cacheTagsView) {
      tagsViewStore.delAllVisitedViews()
      tagsViewStore.delAllCachedViews()
    }
  }

  return { token, roles, username, login, getInfo, changeRoles, logout, resetToken }
})

/** 在 setup 外使用 */
export function useUserStoreHook() {
  return useUserStore(store)
}
